package com.zcc.lock;

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {
        Testlock2 testlock2 = new Testlock2();
        new Thread(testlock2,"t1").start();
        new Thread(testlock2,"t2").start();
        new Thread(testlock2,"t3").start();
    }
}

class Testlock2 implements Runnable {
    int ticketNums = 10;
    //定义lock锁，可重入锁
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true) {
            try{
                //加锁
                lock.lock();
                if (ticketNums > 0) {
                    try {
                        Thread.sleep(1000);
                        System.out.println(ticketNums--);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }else {
                    break;
                }
            }finally {
                //解锁
                lock.unlock();
            }
        }
    }
}
